//
var imgUp = document.getElementById('upload-img');
var imgTit = $('.process-img');
var imgNet = $('.prev-img');
var imgUrl = $('.url-img');
var apiHead = 'http://user.api.hudunsoft.com/v1/';
var apiBack = 'http://liuchengtu.oss-cn-shanghai.aliyuncs.com/';
var b64 = '';
//上传
axios.defaults.data = {
    client: 'web',
    source: '122',
    soft_version: '1.3',
    device_id: ''
}
function up_conv() {
    if (b64 == '') {
        imgTit.html('空 base64 ！');
        imgUrl.html('...');
        return;
    }
    var url = apiHead + 'image/upload';
    var data = {
        img_data: b64,
        ext: 'jpg'
    };
    imgTit.html('上传图片...');
    axios.post(url, data).then(function (res) {
        var str = res.data.data.aliurl;
        imgTit.html(res.data.message);
        imgUrl.html(str.substring(apiBack.length));
        b64 = '';
    }).catch(function (err) {
        imgTit.html(err);
    });
}
function open_url() {
    if (imgUrl.html() == '...') return;
    //这么直接开会被防盗链，只有本地有效
    //手机上只有复制 url重新打开，但已经有效了
    window.open(apiBack + imgUrl.html());
}
//读取，旋转，压缩，显示
function load_pic() {
    imgTit.html('选完开始...');
    var file = imgUp.files[0];
    if (file) {
        photoCompress(file, function () {
            imgTit.html('已经获得 canvas压缩后的 base64');
            var ImgFileSize = b64.substring(b64.indexOf(",") + 1);
            if (b64.length > 209 * 10000) {
                imgTit.html('图片超过 2M ！');
            } else {
                imgTit.html(ImgFileSize.length);
                imgNet.attr('src', b64);
            }
        });
    } else {
        $('.process-img').html('没有文件？？？');
    }
}
function photoCompress(file, callback) {
    // 使用HTML5的FileReader开始读取File对象中的内容
    var setting = {};
    var ready = new FileReader();
    ready.readAsDataURL(file);
    var that = this;
    // 判断图片需不需要压缩
    if (file.size / 1024 < 7000) {
        setting.quality = .9;
    } else if (file.size / 1024 < 15000) {
        setting.quality = .7;
    } else {
        setting.quality = .5;
    }
    // 获取图片源信息 判断照片方向
    ready.onload = function () {
        var _this = this;
        that.getOrientation(file, function (o) {
            setting.orientation = o;
            var re = _this.result;
            that.canvasDataURL(re, setting, callback, file)
        })
    }
}
function getOrientation(img, rot) {
    EXIF.getData(img, function () {
        var o = EXIF.getTag(img, "Orientation");
        rot(o);
    });
}
function canvasDataURL(result, obj, callback) {
    var img = new Image();
    img.src = result;
    var _this = this;
    img.onload = function () {
        var that = this;
        var w, h, scale;
        scale = that.width / that.height;
        if (that.width > 1200) {
            w = 1200;
            h = w / scale;
        } else {
            w = that.width;
            h = that.height;
        }
        //生成canvas
        var canvas = document.createElement('canvas');
        var ctx = canvas.getContext('2d');
        // 创建属性节点
        var anw = document.createAttribute("width");
        anw.nodeValue = w;
        var anh = document.createAttribute("height");
        anh.nodeValue = h;
        canvas.setAttributeNode(anw);
        canvas.setAttributeNode(anh);
        // 调整图片方向
        imgTit.html('照片方向：', obj.orientation);
        if (obj.orientation && obj.orientation != "" && obj.orientation != 1) {
            switch (obj.orientation) {
                case 6: //需要顺时针（向左）90度旋转
                    _this.rotateImg(that, w, h, 'left', canvas, ctx);
                    break;
                case 8: //需要逆时针（向右）90度旋转
                    _this.rotateImg(that, w, h, 'right', canvas, ctx);
                    break;
                case 3: //需要180度旋转，转两次
                    _this.rotateImg(that, w, h, 'right', canvas, ctx);
                    _this.rotateImg(that, w, h, 'right', canvas, ctx);
                    break;
            }
        } else {
            ctx.drawImage(that, 0, 0, w, h);
        }
        // 压缩图像质量
        b64 = canvas.toDataURL('image/jpeg', obj.quality);
        // 回调函数返回base64的值
        callback();
    }
}
function rotateImg(img, w, h, direction, canvas, ctx) {
    //最小与最大旋转方向，图片旋转4次后回到原方向
    var min_step = 0;
    var max_step = 3;
    if (img == null) return;
    //img的高度和宽度不能在img元素隐藏后获取，否则会出错
    var height = h;
    var width = w;
    var step = 2;
    if (direction == 'right') {
        step++;
        //旋转到原位置，即超过最大值
        step > max_step && (step = min_step);
    } else {
        step--;
        step < min_step && (step = max_step);
    }
    //旋转角度以弧度值为参数
    var degree = step * 90 * Math.PI / 180;
    switch (step) {
        case 0:
            canvas.width = width;
            canvas.height = height;
            ctx.drawImage(img, 0, 0);
            break;
        case 1:
            canvas.width = height;
            canvas.height = width;
            ctx.rotate(degree);
            ctx.drawImage(img, 0, -height, w, h);
            break;
        case 2:
            canvas.width = width;
            canvas.height = height;
            ctx.rotate(degree);
            ctx.drawImage(img, -width, -height, w, h);
            break;
        case 3:
            canvas.width = height;
            canvas.height = width;
            ctx.rotate(degree);
            ctx.drawImage(img, -width, 0, w, h);
            break;
    }
}